package com.zzty.zzlp.commom;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;


//解压文件
public class DeCompressUtil {

    private static void unzip(String sourceZip, String destDir) throws Exception {
        try {
            Project p = new Project();
            Expand e = new Expand();
            e.setProject(p);
            e.setSrc(new File(sourceZip));
            e.setOverwrite(false);
            e.setDest(new File(destDir));
            /*
			 * ant下的zip工具默认压缩编码为UTF-8编码， 而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
			 * 所以解压缩时要制定编码格式
			 */
            e.setEncoding("gbk");
            e.execute();
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 解压缩
     */
    public static void deCompress(String sourceFile, String destDir) throws Exception {
        // 保证文件夹路径最后是"/"或者"\"
        char lastChar = destDir.charAt(destDir.length() - 1);
        if (lastChar != '/' && lastChar != '\\') {
            destDir += File.separator;
        }
        // 根据类型，进行相应的解压缩
        String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
        if (type.equals("zip")) {
            DeCompressUtil.unzip(sourceFile, destDir);
            System.out.println("解压成功");
        } else {
            throw new Exception("只支持zip格式的压缩包！");
        }
    }

}